<template>
    <div class="portfolio-management">
        <div class="header">
            <h2>持仓管理</h2>
            <el-button type="primary" @click="showAddDialog">添加持仓</el-button>
        </div>

        <!-- 统计信息卡片 -->
        <el-card class="stats-card">
            <div class="stats-grid">
                <div class="stat-item">
                    <span class="label">总资产</span>
                    <div class="value-wrapper">
                        <span v-if="!editingStats">¥{{ portfolioStats.totalAssets }}</span>
                        <el-input v-else v-model="editingStatsForm.totalAssets" size="small" />
                    </div>
                </div>
                <div class="stat-item">
                    <span class="label">总投入</span>
                    <div class="value-wrapper">
                        <span v-if="!editingStats">¥{{ portfolioStats.totalInvestment }}</span>
                        <el-input v-else v-model="editingStatsForm.totalInvestment" size="small" />
                    </div>
                </div>
                <div class="stat-item">
                    <span class="label">累计收益</span>
                    <div class="value-wrapper">
                        <span :class="['rate', portfolioStats.totalProfitRate >= 0 ? 'positive' : 'negative']">
                            {{ portfolioStats.totalProfitRate >= 0 ? '+' : '' }}{{ portfolioStats.totalProfitRate }}%
                        </span>
                    </div>
                </div>
                <div class="stat-item">
                    <span class="label">在投数量</span>
                    <span class="value">{{ portfolioStats.holdingCount }}支</span>
                </div>
                <el-button 
                    :type="editingStats ? 'success' : 'primary'"
                    link
                    @click="handleStatsEdit"
                >
                    {{ editingStats ? '保存' : '编辑' }}
                </el-button>
            </div>
        </el-card>

        <!-- 持仓列表 -->
        <el-tabs v-model="activeTab" class="portfolio-tabs">
            <el-tab-pane label="当前持仓" name="holding">
                <el-table :data="holdingList" style="width: 100%">
                    <el-table-column prop="name" label="股票名称" />
                    <el-table-column prop="code" label="股票代码" />
                    <el-table-column prop="amount" label="持仓数量" />
                    <el-table-column prop="cost" label="成本价" />
                    <el-table-column prop="current" label="现价" />
                    <el-table-column label="盈亏">
                        <template #default="scope">
                            <span :class="['rate', scope.row.profit >= 0 ? 'positive' : 'negative']">
                                {{ scope.row.profit >= 0 ? '+' : '' }}{{ scope.row.profit }}%
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200">
                        <template #default="scope">
                            <el-button size="small" @click="editHolding(scope.row)">编辑</el-button>
                            <el-button size="small" type="success" @click="moveToClosedDialog(scope.row)">清仓</el-button>
                            <el-button size="small" type="danger" @click="deleteHolding(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="已清仓" name="closed">
                <el-table :data="closedList" style="width: 100%">
                    <el-table-column prop="name" label="股票名称" />
                    <el-table-column prop="code" label="股票代码" />
                    <el-table-column prop="buyPrice" label="买入价" />
                    <el-table-column prop="sellPrice" label="卖出价" />
                    <el-table-column prop="holdDays" label="持有天数" />
                    <el-table-column label="总收益">
                        <template #default="scope">
                            <span :class="['rate', scope.row.totalProfit >= 0 ? 'positive' : 'negative']">
                                {{ scope.row.totalProfit >= 0 ? '+' : '' }}{{ scope.row.totalProfit }}%
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="150">
                        <template #default="scope">
                            <el-button size="small" @click="editClosed(scope.row)">编辑</el-button>
                            <el-button size="small" type="danger" @click="deleteClosed(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>

        <!-- 编辑统计信息对话框 -->
        <el-dialog
            v-model="editingStats"
            title="编辑统计信息"
            width="30%"
        >
            <el-form :model="editingStatsForm" label-width="100px">
                <el-form-item label="总资产">
                    <el-input v-model="editingStatsForm.totalAssets" />
                </el-form-item>
                <el-form-item label="总投入">
                    <el-input v-model="editingStatsForm.totalInvestment" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editingStats = false">取消</el-button>
                    <el-button type="primary" @click="saveStats">保存</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 添加/编辑持仓对话框 -->
        <el-dialog
            v-model="holdingDialogVisible"
            :title="holdingForm.id ? '编辑持仓' : '添加持仓'"
            width="30%"
        >
            <el-form :model="holdingForm" label-width="100px">
                <el-form-item label="股票名称">
                    <el-input v-model="holdingForm.name" />
                </el-form-item>
                <el-form-item label="股票代码">
                    <el-input v-model="holdingForm.code" />
                </el-form-item>
                <el-form-item label="持仓数量">
                    <el-input v-model="holdingForm.amount" type="number" />
                </el-form-item>
                <el-form-item label="成本价">
                    <el-input v-model="holdingForm.cost" type="number" />
                </el-form-item>
                <el-form-item label="现价">
                    <el-input v-model="holdingForm.current" type="number" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="holdingDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitHolding">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 清仓对话框 -->
        <el-dialog
            v-model="closedDialogVisible"
            title="清仓操作"
            width="30%"
        >
            <el-form :model="closedForm" label-width="100px">
                <el-form-item label="卖出价">
                    <el-input v-model="closedForm.sellPrice" type="number" />
                </el-form-item>
                <el-form-item label="持有天数">
                    <el-input v-model="closedForm.holdDays" type="number" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="closedDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitClosed">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import portfolioData from '@/assets/data/portfolio.md?raw'

// 添加调试日志
console.log('Portfolio Data:', portfolioData)

const activeTab = ref('holding')
const editingStats = ref(false)
const holdingList = ref([])
const closedList = ref([])

const editingStatsForm = ref({
    totalAssets: 0,
    totalInvestment: 0
})

// 持仓表单相关
const holdingDialogVisible = ref(false)
const holdingForm = ref({
    id: undefined as number | undefined,
    name: '',
    code: '',
    amount: 0,
    cost: 0,
    current: 0
})

// 清仓表单相关
const closedDialogVisible = ref(false)
const closedForm = ref({
    id: undefined as number | undefined,
    sellPrice: 0,
    holdDays: 0
})

// 修改 portfolioStats 的计算逻辑
const portfolioStats = computed(() => {
    const holdings = holdingList.value
    
    // 计算总资产（每个持仓的现值之和）
    const totalAssets = holdings.reduce((sum, holding) => {
        return sum + (holding.current * holding.amount)
    }, 0)
    
    // 计算总投入（每个持仓的成本之和）
    const totalInvestment = holdings.reduce((sum, holding) => {
        return sum + (holding.cost * holding.amount)
    }, 0)
    
    // 计算累计收益率
    const totalProfitRate = totalInvestment > 0 
        ? ((totalAssets - totalInvestment) / totalInvestment * 100).toFixed(2)
        : '0.00'
    
    // 计算在投数量
    const holdingCount = holdings.length

    return {
        totalAssets: totalAssets.toFixed(2),
        totalInvestment: totalInvestment.toFixed(2),
        totalProfitRate,
        holdingCount
    }
})

// 获取持仓列表
const getHoldingList = () => {
    try {
        console.log('Getting holdings from:', portfolioData)
        const holdingsMatch = portfolioData.match(/## Holdings\s*(\[[\s\S]*?])/m)
        console.log('Holdings match:', holdingsMatch)
        if (holdingsMatch) {
            const holdings = JSON.parse(holdingsMatch[1])
            console.log('Parsed holdings:', holdings)
            holdingList.value = holdings.map((item: any) => ({
                ...item,
                profit: ((item.current - item.cost) / item.cost * 100).toFixed(2)
            }))
        }
    } catch (error) {
        console.error('获取持仓列表失败:', error)
    }
}

// 获取已清仓列表
const getClosedList = () => {
    try {
        const closedMatch = portfolioData.match(/## Closed\s*(\[[\s\S]*?])/m)
        if (closedMatch) {
            const closed = JSON.parse(closedMatch[1])
            closedList.value = closed.map((item: any) => ({
                name: item.name,
                code: item.code,
                buyPrice: item.buy_price,
                sellPrice: item.sell_price,
                holdDays: item.hold_days,
                totalProfit: item.total_profit
            }))
        }
    } catch (error) {
        console.error('获取已清仓列表失败:', error)
    }
}

// 编辑统计信息
const handleStatsEdit = () => {
    if (!editingStats.value) {
        // 开始编辑
        editingStatsForm.value = {
            totalAssets: portfolioStats.value.totalAssets,
            totalInvestment: portfolioStats.value.totalInvestment
        }
    }
    editingStats.value = !editingStats.value
}

// 保存统计信息
const saveStats = () => {
    // 这里应该更新 markdown 文件内容，但由于是静态文件，
    // 我们可以使用 localStorage 来模拟数据持久化
    try {
        const newStats = {
            total_assets: editingStatsForm.value.totalAssets,
            total_investment: editingStatsForm.value.totalInvestment,
            total_profit_rate: ((editingStatsForm.value.totalAssets - editingStatsForm.value.totalInvestment) / editingStatsForm.value.totalInvestment * 100).toFixed(2),
            holding_count: holdingList.value.length
        }
        localStorage.setItem('portfolio_stats', JSON.stringify(newStats))
        ElMessage.success('保存成功')
        editingStats.value = false
    } catch (error) {
        console.error('保存统计信息失败:', error)
        ElMessage.error('保存失败')
    }
}

// 页面加载时获取数据
onMounted(() => {
    getHoldingList()
})

// 监听标签切换
watch(activeTab, (newTab) => {
    if (newTab === 'closed') {
        getClosedList()
    } else {
        getHoldingList()
    }
})

// 显示添加持仓对话框
const showAddDialog = () => {
    holdingForm.value = {
        id: undefined,
        name: '',
        code: '',
        amount: 0,
        cost: 0,
        current: 0
    }
    holdingDialogVisible.value = true
}

// 编辑持仓
const editHolding = (row: any) => {
    holdingForm.value = { ...row }
    holdingDialogVisible.value = true
}

// 提交持仓表单
const submitHolding = () => {
    try {
        const holdings = [...holdingList.value]
        if (holdingForm.value.id) {
            // 更新现有持仓
            const index = holdings.findIndex(h => h.id === holdingForm.value.id)
            if (index !== -1) {
                holdings[index] = { ...holdingForm.value }
            }
        } else {
            // 添加新持仓
            const newId = Math.max(...holdings.map(h => h.id), 0) + 1
            holdings.push({ ...holdingForm.value, id: newId })
        }
        localStorage.setItem('portfolio_holdings', JSON.stringify(holdings))
        ElMessage.success(holdingForm.value.id ? '更新成功' : '添加成功')
        holdingDialogVisible.value = false
        getHoldingList()
    } catch (error) {
        console.error('提交持仓失败:', error)
        ElMessage.error('操作失败')
    }
}

// 显示清仓对话框
const moveToClosedDialog = (row: any) => {
    closedForm.value = {
        id: row.id,
        sellPrice: row.current,
        holdDays: 0
    }
    closedDialogVisible.value = true
}

// 提交清仓操作
const submitClosed = () => {
    try {
        const holdings = [...holdingList.value]
        const closed = [...closedList.value]
        const holding = holdings.find(h => h.id === closedForm.value.id)
        
        if (holding) {
            const newClosed = {
                id: Math.max(...closed.map(c => c.id), 0) + 1,
                name: holding.name,
                code: holding.code,
                buy_price: holding.cost,
                sell_price: closedForm.value.sellPrice,
                hold_days: closedForm.value.holdDays,
                total_profit: ((closedForm.value.sellPrice - holding.cost) / holding.cost * 100).toFixed(2)
            }
            
            closed.push(newClosed)
            localStorage.setItem('portfolio_closed', JSON.stringify(closed))
            
            // 从持仓列表中删除
            const newHoldings = holdings.filter(h => h.id !== closedForm.value.id)
            localStorage.setItem('portfolio_holdings', JSON.stringify(newHoldings))
            
            ElMessage.success('清仓成功')
            closedDialogVisible.value = false
            getHoldingList()
            getClosedList()
        }
    } catch (error) {
        console.error('清仓操作失败:', error)
        ElMessage.error('操作失败')
    }
}

// 删除持仓
const deleteHolding = (row: any) => {
    ElMessageBox.confirm(
        '确定要删除这条持仓记录吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        try {
            const holdings = holdingList.value.filter(h => h.id !== row.id)
            localStorage.setItem('portfolio_holdings', JSON.stringify(holdings))
            ElMessage.success('删除成功')
            getHoldingList()
        } catch (error) {
            console.error('删除持仓失败:', error)
            ElMessage.error('删除失败')
        }
    }).catch(() => {})
}

// 删除已清仓记录
const deleteClosed = (row: any) => {
    ElMessageBox.confirm(
        '确定要删除这条清仓记录吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        try {
            const closed = closedList.value.filter(c => c.id !== row.id)
            localStorage.setItem('portfolio_closed', JSON.stringify(closed))
            ElMessage.success('删除成功')
            getClosedList()
        } catch (error) {
            console.error('删除清仓记录失败:', error)
            ElMessage.error('删除失败')
        }
    }).catch(() => {})
}
</script>

<style scoped>
.portfolio-management {
    width: 100%;
    height: 100%;
    padding: 20px;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.stats-card {
    margin-bottom: 20px;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    position: relative;
}

.stat-item {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.label {
    font-size: 14px;
    color: #666;
}

.value {
    font-size: 20px;
    font-weight: 500;
}

.rate {
    font-weight: 500;
}

.positive {
    color: #F56C6C;
}

.negative {
    color: #67C23A;
}

.portfolio-tabs {
    margin-top: 20px;
}

.value-wrapper {
    display: flex;
    align-items: center;
    gap: 8px;
}

:deep(.el-input) {
    width: 120px;
}
</style> 